<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2020/5/17
 * Time: 12:38
 */

namespace app\admin\service\business\controllers\Auth;


use app\admin\service\business\BaseControllerService;
use app\admin\service\business\controllers\Access\Action\ActionService;
use app\admin\service\business\controllers\Auth\Models\AuthModel;
use app\admin\service\business\controllers\Auth\Traits\Auth;
use app\admin\service\specification\token\TokenInterface;

/**
 * Class AuthService
 *
 * @property-read AuthModel $model
 *
 * @package app\admin\service\business\controllers\Auth
 */
class AuthService extends BaseControllerService
{
    use Auth;

    protected $rely = [
        'model' => AuthModel::class
    ];

    /**
     * 登录
     *
     * @param TokenInterface $token
     * @param string $username
     * @param string $password
     * @return array
     */
    public function login(TokenInterface $token, string $username, string $password){
        // 用户是否存在
        if(!$user = $this -> model -> getUserInfo($username)) return echoArr(600);

        // 密码是否错误
        if(sha1($password . config('app.key')) != $user -> password) return echoArr(600);

        // 用户是否启用
        if(!$user -> status) return echoArr(601);

        // 设置 session
        $token -> set($token -> get(), ['id' => $user['id']]);

        // 记录日志
        ActionService::getInstance() -> operating([
            'user_id' => $user -> id,
            'path' => request()->rule()->getRule(),
            'method' => request()->method(),
            'ip' => request()->ip(),
            'input' => json_encode(request()->param(['username', 'code']))
        ]);

        return echoArr(200);
    }

    /**
     * 退出登录
     *
     * @param TokenInterface $token
     */
    public function logout(TokenInterface $token){
        $token -> clear($token -> get());
    }
}
